package ar.edu.itba.pod.printer.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import ar.edu.itba.pod.printer.Document;
import ar.edu.itba.pod.printer.Printer;
import ar.edu.itba.pod.printer.PrinterDispatcher;

public class EnhancedAsyncPrinterDispatcher implements PrinterDispatcher{

	private Printer printer= new Printer();
	private BlockingQueue<Document> queue = new LinkedBlockingQueue<Document>(5);
	private MyThread thread = new MyThread() {
		
		@Override
		public void excecute() {
			printIfQueueNotEmpty();
		}
	};;;
	private long timeout;
	private Document lastDocument;
	
	public EnhancedAsyncPrinterDispatcher(int timeout) {
		thread.start();
		this.timeout=timeout;
	}
	@Override
	public void printDocument(Document document) {
		try {
			if((!queue.offer(document,this.timeout, TimeUnit.MILLISECONDS) && 
					(lastDocument!=null))){
				System.out.print('x');
				queue.remove(lastDocument);
				// que onda la excepcion tengo que cambiar el signature?
//				throw new TimeoutException();
			};
			lastDocument=document;
		} catch (InterruptedException e) {
			finishPrintRequests();
		}
	}

	@Override
	public void finishPrintRequests() {
		printIfQueueNotEmpty();
		thread.finish();
	}
	
	public void printIfQueueNotEmpty(){
		if(!queue.isEmpty()){
			try {
				printer.print(queue.take());
			} catch (InterruptedException e) {
				finishPrintRequests();
			}
		}
	}

}
